package com.tj.collection.task;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.api.Page;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.tj.collection.db.dao.ClCallDurationDao;
import com.tj.collection.db.entity.ClCallDurationEntity;
import com.tj.collection.utils.ConfigUtil;
import com.tj.collection.utils.TextFormatUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: pavan
 * Date: 2020/3/25
 * Time: 下午2:10
 */
@Component
public class FFmpegTranscodingTask implements SimpleJob {

    private static final Log LOGGER = LogFactory.getLog(FFmpegTranscodingTask.class);

    private static final String DIR_TMP = "/home/fqgj/tmp/";

    @Autowired
    private OSSService ossService;

    @Autowired
    private ConfigUtil configUtil;

    @Autowired
    private ClCallDurationDao clCallDurationDao;

    @Override
    public void execute(ShardingContext shardingContext) {
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
        }
        if (!configUtil.getFfmpegConvertIp().equals(ip)) {
            LOGGER.info("本机不执行音频转换任务,ip:{}", ip);
            return;
        }
        if (!configUtil.getFfmpegConvertToMp3Switch()) {
            LOGGER.info("录音转换任务暂停,ip:{}", ip);
            return;
        }

        LOGGER.info("录音转换任务开始");

        List<ClCallDurationEntity> clCallDurationEntityList = clCallDurationDao.selectWaitConvertCallDurationList(new Page(1000));
        for (ClCallDurationEntity entity : clCallDurationEntityList) {

            String url1 = entity.getVideoUrl();
//            if (!configUtil.isServerTest()) {
//                url1 = configUtil.getInternalUrl(url1);
//            }

            String url2 = null;
            try {
                url2 = this.convertAmrToMp3Url(url1);
            } catch (Exception e) {
                LOGGER.error("录音转换异常,entity:{}", JSON.toJSONString(entity));
                continue;
            }
            if (StringUtils.isEmpty(url2)) {
                LOGGER.error("录音转换失败,entity:{}", JSON.toJSONString(entity));
                continue;
            }
            entity.setVideoUrl2(url2);
            clCallDurationDao.updateByPrimaryKey(entity);
        }
        LOGGER.info("录音转换任务结束,size:{}", clCallDurationEntityList.size());
    }

    /**
     * 附ffmpeg安装帖：https://www.cnblogs.com/joshua317/articles/5478622.html
     * 转换机器使用172.31.2.112
     *
     * @param url
     * @return
     */
    public String convertAmrToMp3Url(String url) {
        if (url == null || !url.endsWith(".amr")) {
            throw new ApplicationException("文件类型不匹配");
        }

        String s1 = url.split("//")[1];
        String s2 = s1.substring(s1.indexOf("/") + 1);

        int index = s2.lastIndexOf("/");
        String dir = index < 0 ? "" : s2.substring(0, index + 1);
        String sourceFileName = s2.substring(index + 1);

        String targetFileName = sourceFileName.replaceAll("\\.amr", ".mp3");

        LOGGER.info("准备文件转换,url:{}", url);

        File sourceFile = null;
        try {
            URL httpUrl = new URL(url);
            sourceFile = new File(DIR_TMP + sourceFileName);
            FileUtils.copyURLToFile(httpUrl, sourceFile);
        } catch (Exception e) {
            LOGGER.error("下载文件失败,url:{}", url, e);
            throw new ApplicationException("下载文件失败");
        }

        String result = "";
        Process process = null;
        try {
            String command = TextFormatUtil.format("sh {DIR_TMP}convertAmrToMp3.sh {DIR_TMP}{sourceFileName} {DIR_TMP}{targetFileName}",
                    DIR_TMP, DIR_TMP, sourceFileName, DIR_TMP, targetFileName);
            process = Runtime.getRuntime().exec(command);
            LOGGER.info("开始转换,command:{}", command);
            process.waitFor();
            LOGGER.info("转换结束");
        } catch (Exception e) {
            LOGGER.error("amr转mp3失败,url:{}", url, e);
            throw new ApplicationException("转换文件失败");
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        File targetFile2 = new File(DIR_TMP + targetFileName);
        if (!targetFile2.exists()) {
            throw new ApplicationException("转换后的文件不存在");
        }
        String targetFileFullName = dir + targetFileName;
        LOGGER.info("准备上传到OSS,targetFileName:{},targetFileFullName:{}", (DIR_TMP + targetFileName), targetFileFullName);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(targetFile2);
            ossService.uploadFile(configUtil.getOssImageBuketName(), inputStream, inputStream.available(), targetFileFullName);
            result = configUtil.getQsyqBaseUrl() + targetFileFullName;
        } catch (IOException e) {
            LOGGER.error("上传文件失败", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                }
            }
            if (sourceFile.exists()) {
                if (!sourceFile.delete()) {
                    LOGGER.warn("删除旧文件失败,sourceFileName:{}", sourceFileName);
                }
            }
            if (targetFile2.exists()) {
                if (!targetFile2.delete()) {
                    LOGGER.warn("删除新文件失败,targetFileName:{}", targetFileName);
                }
            }
        }
        LOGGER.info("文件转换并上传,result:{}", result);
        return result;
    }

    public static void main(String[] args) {

        func2("https://loanzone.oss-ap-south-1.aliyuncs.com/app/email_template/basicTemplate_2.html");

        System.out.println("1111111111");

        func2("https://loanzone.oss-ap-south-1.aliyuncs.com/basicTemplate_2.html");
        System.out.println("22222222");
        func2("https://loanzone.oss-ap-south-1.aliyuncs.com/app/xxxx.amr");
        System.out.println("333333333");
        func2("https://loanzone.oss-ap-south-1.aliyuncs.com/app/aaa/bbb/ccc/ddd/xxxx.amr");
    }


    public static void func2(String url) {
        String s1 = url.split("//")[1];
        String s2 = s1.substring(s1.indexOf("/") + 1);

        System.out.println(s1);
        System.out.println(s2);

        int index = s2.lastIndexOf("/");
        String dir = index < 0 ? "" : s2.substring(0, index + 1);
        String fileName = s2.substring(index + 1);
        System.out.println("dir=" + dir);
        System.out.println("fileName=" + fileName);
    }
}
